<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: backup.php 11 2013-09-21 11:43:11Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 11 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 11:43:11 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright © since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	© 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	© 2002-2003 osCommerce - www.oscommerce.com
* 	© 2003     nextcommerce - www.nextcommerce.org
* 	© 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

$data = '# SEO:mercari'."\n" .
          '# http://www.seo-mercari.de/'."\n" .
          '#'."\n" .
          '# Datenbank BackUp für '.STORE_NAME."\n" .
          '# Copyright © '.date('Y').' '.STORE_OWNER."\n" .
          '#'."\n" .
          '# Datenbank: '.DB_DATABASE."\n" .
          '# Datenbank Server: '.DB_SERVER."\n" .
          '#'."\n" .
          '# Backup Datum: '.date(PHP_DATE_TIME_FORMAT)."\n\n";

if($_POST['save_table'] == 'complete')
	$data .= export_database($_POST['table']);

elseif($_POST['save_table'] == 'only_fields') {
	for($i=0;$i<=sizeof($_POST['table']);$i++) {
		if(!empty($_POST['table'][$i]))
			$data .= export_table_structure($_POST['table'][$i])."\n";
	}
} elseif($_POST['save_table'] == 'only_data') {
	for($i=0;$i<=sizeof($_POST['table']);$i++) {
		if(!empty($_POST['table'][$i]))
			$data .= export_table_data($_POST['table'][$i]);
	}
} elseif($_POST['save_table'] == 'fields_data') {
	for($i=0;$i<=sizeof($_POST['table']);$i++) {
		if(!empty($_POST['table'][$i])) {
			$data .= export_table_structure($_POST['table'][$i]);
			$data .= export_table_data($_POST['table'][$i])."\n";
		}
	}
}

$backup_file = 'db_'.DB_DATABASE.'_'.date('Y-m-d-H-i-s').'.sql';
switch($_POST['compress']) {
	case 'sql':
		if ($fp = fopen(DIR_FS_BACKUP.$backup_file, 'w')) {
			fputs($fp, $data);
			fclose($fp);
		}
		header('Content-type: application/x-octet-stream');
		header('Content-disposition: attachment; filename='.$backup_file);
		echo $data;
		break;
		
	case 'gzip':
		if ($fp = fopen(DIR_FS_BACKUP.$backup_file, 'w')) {
			fputs($fp, $data);
			fclose($fp);
			
			include(DIR_WS_CLASSES.'class.zip.php');
			$gzip = new gzip_file($backup_file.'.tgz');
			$gzip->set_options(array('basedir' => DIR_FS_BACKUP, 'level' => 8));
			$gzip->add_files($backup_file);
			$gzip->create_archive();
			@unlink(DIR_FS_BACKUP.$backup_file);
			
			if($fp = fopen(DIR_FS_BACKUP.$backup_file.'.tgz', 'r')) {
				$buffer = fread($fp, filesize(DIR_FS_BACKUP.$backup_file.'.tgz'));
				fclose($fp);
				header('Content-type: application/x-gzip');
				header("Content-Transfer-Encoding: binary");
				header('Content-disposition: attachment; filename='.$backup_file.'.tgz');
				echo $buffer;
				exit;
			}
		}
		break;
		
	case 'zip':
		if ($fp = fopen(DIR_FS_BACKUP.$backup_file, 'w')) {
			fputs($fp, $data);
			fclose($fp);

			include(DIR_WS_CLASSES.'class.zip.php');
			$zip = new zip_file('../'.$backup_file.'.zip');
			$zip->set_options(array('inmemory' => 1, 'recurse' => 0, 'storepaths' => 0));
			$zip->add_files('backups/'.$backup_file);
			$zip->create_archive();
			$zip->download_file();
		}
		break;
}

function export_table_structure($table, $drop_if_exists = true, $break = "\n") {
	global $db;
	
	$break = ($break == "\n" OR $break == "\r\n" OR $break == "\r") ? $break : "\n";

	$sqlstring = "";

	if($drop_if_exists)
		$sqlstring .= "DROP TABLE IF EXISTS ".$table.";".$break;

	$data = $db->db_query("SHOW CREATE TABLE ".$table);

	$sqlstring .= str_replace("\n", $break, $data->fields['Create Table']) . ";$break$break";

	return $sqlstring;
}

function export_table_data($table, $leave_out_fields = false, $break = "\n") {
	global $db;
	
	$break = ($break == "\n" OR $break == "\r\n" OR $break == "\r") ? $break : "\n";

	$data = $db->db_query("SELECT * FROM ".$table);

	$sqlstring = "";

	while(!$data->EOF) {
		$keys = array();
		$values = array();
		foreach($data->fields as $key => $value) {
			if(is_array($leave_out_fields) AND in_array($key, $leave_out_fields))
				continue;

			$keys[] = $key;
			if($value === NULL)
				$value = "NULL";

			elseif($value === "" OR $value === false)
				$value = "''";

			elseif(!is_numeric($value))
				$value = $db->db_prepare($value);
				
			$values[] = $value;
		}
		$sqlstring .= "INSERT INTO ".$table." (".implode(", ",$keys).") VALUES (".implode(", ", $values).");".$break;
		$data->MoveNext();
	}
	$sqlstring .= $break;
    return $sqlstring;
}

function export_database($tables_input = false, $break = "\n") {
	$db = DB_DATABASE;
	
	$break = ($break == "\n" OR $break == "\r\n" OR $break == "\r") ? $break : "\n";

	$tables = array();

	if(is_array($tables_input))
		$tables = $tables_input;

	elseif(!is_array($tables_input) AND $tables_input)
		$tables[0] = $tables_input;

	else
		$tables = get_tables();

	foreach($tables as $table) {
		$exportstring .= "# Tabelle: ".$table.$break;
		$exportstring .= export_table_structure($table, true, $break);
		$exportstring .= export_table_data($table, false, $break);
		$exportstring .= $break;
	}

	return $exportstring;
}

function get_tables() {
	global $db;
	
	$data = $db->db_tables();

    $tables = array();
    while(list(,$table) = each($data))
        $tables[] = $table;

    return $tables;
}